import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtActionSheet, AtIcon, AtToast, AtInputNumber } from 'taro-ui'
import { connect } from '@tarojs/redux'
import './dLinearLayout.scss'
import { State, Props } from '../detail.interface'

@connect(({ detail }) => ({
  ...detail,
}))

export class Sku extends Component<State, Props> {
  state = {
    openAtAction: false,
    buyNum: 1,
    toast: {
      isOpened: false,
      status: 'error',
      text: ''
    }
  }
  constructor(props: Props) {
    super(props);

  }
  componentDidMount() {
  }

  handleShowAtAction() {
    this.setState({
      openAtAction: true
    });
  }

  handleCloseAtAction() {
    this.setState({
      openAtAction: false
    });
  }

  handleSelectSku(nameId, valueId) {
    const { dispatch } = this.props;
    dispatch({
      type: 'detail/selectSku',
      payload: {
        name_id: nameId,
        value_id: valueId
      }
    })
  }

  //输出最多两个sku name
  handleSkuName() {
    const { data } = this.props;
    let skuName = '选择';
    let selectedName = '已选择';
    if (data.sku) {
      for (let i = 0; i < data.sku.length; i++) {
        let tmpSelected = false;
        for (let j = 0; j < data.sku[i].skuValue.length; j++) {
          if (data.sku[i].skuValue[j].selected == 1) {
            selectedName += ' ' + data.sku[i].skuValue[j].value;
            tmpSelected = true;
          }
        }

        if (!tmpSelected) {
          skuName += ' ' + data.sku[i].name;
        }

        if (i == 1) {
          break;
        }
      }
    }
    return skuName === '选择' ? selectedName : skuName;
  }

  handleBuyNum(type) {
    const { buyNum } = this.state;
    if (type === 'subtract' && buyNum > 1) {
      this.setState({
        buyNum: buyNum - 1
      });
    } else if (type === 'add') {
      this.setState({
        buyNum: buyNum + 1
      });
    }
  }

  handleChange(value) {
    this.setState({
      buyNum: value
    });
  }

  handleAddCart() {
    const { data, dispatch } = this.props;
    const { buyNum } = this.state;
    let payload = {
      id: data.id,
      store_id: data.stores_id,
      quantity: buyNum,
      sku: []
    }

    //没有选择的规格
    let skuNameNotice = '';
    if (data.sku && data.sku.length > 0) {
      for (let i = 0; i < data.sku.length; i++) {
        let skuNameSelectd = false;
        for (let j = 0; j < data.sku[i].skuValue.length; j++) {
          if (data.sku[i].skuValue[j].selected === 1) {
            payload.sku.push(data.sku[i].skuValue[j].id);
            skuNameSelectd = true;
          }
        }
        if (!skuNameSelectd) {
          skuNameNotice += data.sku[i].name + ' ';
        }
      }
    }
    if (skuNameNotice != '') {
      this.setState({
        ...this.state,
        toast: {
          isOpened: true,
          status: 'error',
          text: "请选择 " + skuNameNotice
        }
      });
      return;
    }

    dispatch({
      type: 'detail/addCart',
      payload
    })
  }

  handleToastClose() {
    this.setState({
      toast: {
        isOpened: false,
        status: 'error',
        text: '请选择规格'
      }
    });
  }

  render() {
    const { openAtAction, buyNum, toast } = this.state;
    const { data } = this.props;

    let skuName = '';
    let showSkuValue = [];
    let skuNameCount = 0;
    let showed = false;
    if (data.sku && data.sku.length > 0) {
      for (let i = 0; i < data.sku.length; i++) {
        let sku = data.sku;
        if (sku[i].has_thumbnail) {
          skuName = sku[i].name;
          skuNameCount = sku[i].skuValue.length;
          showSkuValue = sku[i].skuValue;
          showed = true;
        }
      }
      if (!showed) {
        skuName = data.sku[0].name;
        skuNameCount = data.sku[0].skuValue.length;
        showSkuValue = { ...data.sku[0].skuValue };
      }
    }

    return (
      <View className='atAction-content'>
        <AtToast isOpened={toast.isOpened} text={toast.text} duration={500} onClose={() => { this.handleToastClose() }} ></AtToast>
        <View className='dLinearLayout' onClick={() => this.handleShowAtAction()}>
          <View className='dLinearLayout-left'>选择</View>
          <View className='dLinearLayout-center'>
            <View className='dLinearLayout-content'>
              <View className='black'>{this.handleSkuName()}</View>
            </View>
            <View className='dLinearLayout-content mt20'>
              <View className='dLinearLayout-sku mr8'>
                <View className='dLinearLayout-sku-image'>
                  {
                    showed
                      ?
                      showSkuValue.map(function (value) {
                        return <Image className='sku-thumbnail' src={value.thumbnail} mode='widthFix' />
                      })
                      :
                      <View className='sku-value-content'>
                        {
                          showSkuValue.map(function (value) {
                            return <View className='sku-value'>{value.value}</View>
                          })
                        }
                      </View>
                  }
                </View>
                <Text className="sku-more">共{skuNameCount}种{skuName}可选</Text>
              </View>
            </View>
          </View>
          <View className='dLinearLayout-right'>
            <AtIcon value='chevron-right' size='16' color='#8d8d8d'></AtIcon>
          </View>
        </View>

        <AtActionSheet isOpened={openAtAction}>
          <View className='at-content' style={{ overflow: 'hidden' }}>
            <View className='sku-goods-info'>
              <View className='sku-goods-image'>
                <Image className="sku-thumbnail" src={data.thumbnail} mode='widthFix' />
              </View>
              <View className='sku-goods-price'>
                <View className='sku-goods-price-value'>￥{data.selling_price}</View>
                <View className='sku-goods-stock'>库存{data.stock}件</View>
                <View className='sku-goods-selected'>{this.handleSkuName()}</View>
              </View>
              <View className='sku-close-icon' onClick={() => this.handleCloseAtAction()}>
                <AtIcon value='close-circle' size='20' color='#717171'></AtIcon>
              </View>
            </View>
            <View className='at-content-scroll'>
              {
                data.sku && data.sku.map(function (sku) {
                  return (
                    <View className='sku-content'>
                      <View className='sku-name'>{sku.name}</View>
                      <View className='sku-value'>
                        {
                          sku.skuValue.map(function (skuValue) {
                            return skuValue.thumbnail ?
                              <View className={`sku-value-item ${skuValue.selected == 1 ? "sku-value-item-active" : null}`} onClick={this.handleSelectSku.bind(this, sku.id, skuValue.id)}>
                                <View className="sku-value-item-image" >
                                  <Image src={skuValue.thumbnail} mode='widthFix' />
                                </View>
                                {skuValue.value}
                              </View>
                              :
                              <View className={`sku-value-item ${skuValue.selected == 1 ? "sku-value-item-active" : null}`} onClick={this.handleSelectSku.bind(this, sku.id, skuValue.id)}>
                                {skuValue.value}
                              </View>
                          })
                        }
                      </View>
                    </View>
                  )
                }
              }

              <View className='sku-buy-num'>
                <View className='sku-buy-title'>购买数量</View>
                <View className='sku-buy-do'>
                  {/* <View className='subtract' onClick={ () => this.handleBuyNum('subtract')}><AtIcon value='subtract' size='18' color='#717171'></AtIcon></View>
                  <View className="sku-buy-input"> */}
                  <AtInputNumber min={1} max={100} step={1} value={buyNum} onChange={this.handleChange.bind(this)} />
                  {/* </View>
                  <View className='add' onClick={ () => this.handleBuyNum('add')}><AtIcon value='add' size='18' color='#717171'></AtIcon></View> */}
                </View>
              </View>
            </View>
          </View>
          <View className='at-button'>
            <View className='buy-button'>
              <View className='add-cart' onClick={() => this.handleAddCart()}>加入购物车</View>
              <View className='buy-now'>立即购买</View>
            </View>
          </View>
        </AtActionSheet>
      </View>
    )
  }
}